import pathlib
from uuid import uuid4

from django.conf import settings
from django.http import JsonResponse
from django.views.decorators.http import require_http_methods

from gongyequ.decorator import login_required


@require_http_methods(['POST'])
@login_required()
def survey_files(request):
    """文件上传统一接口
    POST /industrialapi/surveyitem/files

    body 为 multipart/form-data 格式
    其他参数：
    filename: [可选] 下载时文件名
    bucket:   [必选] 用途，例如 survey 中上传的图片 user 中上传的头像等
    """
    file = list(request.FILES.values())[0]

    try:
        key = generate_key(
            request.POST.get('bucket'),
            file=file,
            filename=request.POST.get('filename')
        )
        write_file(file, key)
    except Exception:
        return JsonResponse(dict(message='bad request', status=False, code=400, data=[]))

    return JsonResponse(dict(key=key, url=get_media_url(key), filename=file.name))


def generate_key(bucket, file=None, filename=None):
    if not bucket:
        raise Exception('bucket 不能为空！')

    if not file and not filename:
        raise Exception('file、filename 不能都为空！')

    filename = filename or file.name
    ext = pathlib.Path(filename).suffix
    uuid = uuid4().hex

    return f'{bucket}/{uuid[:2]}/{uuid}{ext}'


def write_file(file, key):
    dest = pathlib.Path(settings.MEDIA_ROOT) / key
    dest.parent.mkdir(parents=True, exist_ok=True)

    with open(dest, 'wb+') as f:
        for chunk in file.chunks():
            f.write(chunk)


def get_media_url(key):
    return f'{settings.MEDIA_URL}{key}'
